PEP647 TypeGuardの簡単な紹介
The Global Dev Study #5 - Future of Python でlangaさんが紹介
PEP 647 – User-Defined Type Guards
静的型チェッカーのためのもの
以下を解決したい
code:python
def is_str_list(val: Listobject) -> bool:
"""Determines whether all objects in the list are strings"""
return all(isinstance(x, str) for x in val)
def func1(val: Listobject):
if is_str_list(val):
print(" ".join(val)) # Error: invalid type
解決方法
これでfunc1での書き方がErrorにならない
検証:https://nikkie-ftnext.hatenablog.com/entry/notice-typeguard-use-case-first-time
code:python
def is_str_list(val: Listobject) -> TypeGuard[Liststr]:
"""Determines whether all objects in the list are strings"""
return all(isinstance(x, str) for x in val)